#from fdict import FDict
from collections import defaultdict
import pdb
from types import TupleType
class KWDict(dict):
    def __init__(self,fdict):
       self.xingdict = {}
       self.fdict = fdict
       self.__update__()

    def __update__(self):
        kwdict = defaultdict(list)
        for fname in self.fdict.keys():
            for key in self.fdict[fname]:
                kwdict[key].append(fname)
        self.clear()
        self.update(kwdict)

    def fileXing(self,*keys):
        #pdb.set_trace()
        if(type(keys) != list):
            klist = list(list(keys)[0] )
            nlist = klist[:]
        NOT_files = []
        for tag in nlist:
            if tag[:2] == "N:":
	    	#pdb.set_trace()
                NOT_files.extend(self[ tag[2:] ])
                klist.remove(tag)
        
        if len(klist) is 0: return []
        klist.sort()
        kid = " ".join(nlist)
        if self.xingdict.__contains__(kid):
            return self.xingdict[kid]
        l = lambda val:len(self[val])
        kbylen = sorted(klist,key=l )
        kbylen.reverse()
        xfiles = self[kbylen[0]]
        for key in kbylen:
            xfiles = set(xfiles).intersection(self[key])
        xfiles = set(xfiles) - set(NOT_files)
        self.xingdict[kid] = list(xfiles)
        return list(xfiles);
